import React, { useState,useRef } from 'react';
import marked from 'marked';

let typeTimer = null

function App() {
  const [displayText, setDisplayText] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const contentRef = useRef(null)
  const aiDataRef = useRef({
    aiThoughtText: '',//已接收到的流数据的思考文字
    aiResultText: '',//已接收到的流数据的思考文字
    displayedTextLength: 0,//当前已打字显示出来的文字长度
    loading: false,//ai接口获取数据中
    closed: true//是否关闭当前AI数据分析模块
  })
  let aiConfig={
    dataAnalysisUrl:'/api/v1/chat/completions',
    key:'key'
}
let params=   {"messages":'data'}
function clearAiAnalysis(){
  // 停止打字机效果
  if (typeTimer) {
    clearInterval(typeTimer);
    typeTimer = null;
  }
  
  // 重置AI数据状态
  aiDataRef.current = {
    aiThoughtText: '',
    aiResultText: '',
    displayedTextLength: 0,
    loading: false,
    closed: true
  };
  
  // 清空显示文本
  setDisplayText('');
  
  // 重置加载状态
  setIsLoading(false);
}
const handle = async () => {
    setIsLoading(true);
    aiDataRef.current.closed = false;
    
        fetch(aiConfig?.dataAnalysisUrl, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              Authorization: `Bearer ${aiConfig?.key}`,
            },
            body: JSON.stringify(params),
          }).then(async (response) => {
            const reader = response?.body?.getReader();
            const textDecoder = new TextDecoder();

            startTypewriter()

            while (true) {
              const { done, value } = await reader.read();

              if (done) {
                aiDataRef.current.loading = false
                setIsLoading(false)
                break;
              }
              if (aiDataRef.current.closed) {
                clearAiAnalysis()
                break;
              }
              const chunkText = textDecoder.decode(value);
              const strList = chunkText.match(/data: (.+)/g);

              for (let item of strList) {
                const strItem = item.substring(6)
                if (item?.trim() == '[DONE]' || strItem?.trim() == '[DONE]') {
                  aiDataRef.current.loading = false
                  setIsLoading(false)
                  break;
                } else {
                  const data = JSON.parse(strItem)
                  if (typeof data == 'object' && data?.choices[0]?.delta) {
                    const thoughtText = data?.choices?.[0]?.delta?.reasoning_content || '';
                    const resultText = data?.choices?.[0]?.delta?.content || ''
                    if (thoughtText) {
                      aiDataRef.current.aiThoughtText += thoughtText
                    } else if (resultText) {
                      aiDataRef.current.aiResultText += resultText
                    }
                  }
                }
              }
            }
          }).catch((error) => {
            console.error('AI分析请求失败:', error);
            clearAiAnalysis();
          })

        }


  //ai数据分析打字逻辑
  const startTypewriter = () => {
    let thoughtIndex = 0
    let resultIndex = 0
    if (!typeTimer) {
      aiDataRef.current.loading = true

      typeTimer = setInterval(() => {
        const thoughtText = aiDataRef?.current?.aiThoughtText
        const resultText = aiDataRef?.current?.aiResultText
        //是否请求仍在继续
        const isLoading = aiDataRef?.current?.loading
        const originalText = thoughtText + resultText
        const showTextLength = aiDataRef?.current?.displayedTextLength || 0
        //正在打字中，且接口没有停顿
        if (showTextLength < originalText?.length) {
          aiDataRef.current.displayedTextLength += 1
          const currentText = originalText?.slice(0, aiDataRef.current.displayedTextLength)
          setDisplayText(currentText)
          
          if (contentRef.current) {
            contentRef.current.scrollTop = contentRef.current.scrollHeight >= contentRef.current.clientHeight ? contentRef.current.scrollHeight - contentRef.current.clientHeight : 0;
          }
        } else if (showTextLength >= originalText?.length && !isLoading) {
          setIsLoading(false)
          clearInterval(typeTimer);
          typeTimer = null
        }
      }, 50); // 每30ms显示一个字符，提升打字机效果
    }
  };

  return (
    <div style={{ padding: '20px', fontFamily: 'Arial, sans-serif' }}>
      <h1>AI 数据分析</h1>
      <button 
        onClick={handle} 
        disabled={isLoading}
        style={{
          padding: '10px 20px',
          fontSize: '16px',
          backgroundColor: isLoading ? '#ccc' : '#007bff',
          color: 'white',
          border: 'none',
          borderRadius: '5px',
          cursor: isLoading ? 'not-allowed' : 'pointer'
        }}
      >
        {isLoading ? '分析中...' : 'AI分析'}
      </button>
      
      {/* AI接口返回的数据进行页面按打字机效果进行展示 */}
       <div style={{
         marginTop: '20px',
         padding: '15px',
         border: '1px solid #ddd',
         borderRadius: '5px',
         backgroundColor: '#f9f9f9',
         minHeight: '200px',
         lineHeight: '1.6'
       }}>
         {displayText ? (
            <div 
              className="markdown-content"
              dangerouslySetInnerHTML={{ __html: marked.parse(displayText) }}
              style={{ wordBreak: 'break-word' }}
            />
          ) : (
           <div style={{ color: '#666' }}>
             {isLoading ? '正在获取AI分析结果...' : '点击按钮开始AI分析'}
           </div>
         )}
         {displayText && <span style={{ animation: 'blink 1s infinite' }}>|</span>}
       </div>
      
      <style>{`
         @keyframes blink {
           0%, 50% { opacity: 1; }
           51%, 100% { opacity: 0; }
         }
         
         /* Markdown样式 */
         .markdown-content h1, .markdown-content h2, .markdown-content h3 {
           color: #333;
           margin-top: 20px;
           margin-bottom: 10px;
         }
         
         .markdown-content h1 {
           font-size: 24px;
           border-bottom: 2px solid #eee;
           padding-bottom: 8px;
         }
         
         .markdown-content h2 {
           font-size: 20px;
         }
         
         .markdown-content h3 {
           font-size: 16px;
         }
         
         .markdown-content p {
           margin: 10px 0;
         }
         
         .markdown-content ul, .markdown-content ol {
           margin: 10px 0;
           padding-left: 20px;
         }
         
         .markdown-content li {
           margin: 5px 0;
         }
         
         .markdown-content code {
           background-color: #f4f4f4;
           padding: 2px 4px;
           border-radius: 3px;
           font-family: 'Courier New', monospace;
         }
         
         .markdown-content pre {
           background-color: #f4f4f4;
           padding: 10px;
           border-radius: 5px;
           overflow-x: auto;
           margin: 10px 0;
         }
         
         .markdown-content pre code {
           background: none;
           padding: 0;
         }
         
         .markdown-content blockquote {
           border-left: 4px solid #ddd;
           margin: 10px 0;
           padding-left: 15px;
           color: #666;
         }
         
         .markdown-content table {
           border-collapse: collapse;
           width: 100%;
           margin: 10px 0;
         }
         
         .markdown-content th, .markdown-content td {
           border: 1px solid #ddd;
           padding: 8px;
           text-align: left;
         }
         
         .markdown-content th {
           background-color: #f2f2f2;
         }
       `}</style>
    </div>
  );
}

export default App;